package com.hxzy.bbs.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.hxzy.jsp.connection.JNDIBBSConection;
import com.hxzy.jsp.entity.User;
import com.hxzy.jsp.session.ErrorCode;
import com.hxzy.jsp.utils.Hashs;
import com.mysql.jdbc.StringUtils;

public class RegisterTest extends AppServlet {

	private static final long serialVersionUID = 1L;

	public RegisterTest() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String nickname = request.getParameter("nickname");
		String email = request.getParameter("email");

		if (StringUtils.isEmptyOrWhitespaceOnly(username)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}
		if (StringUtils.isEmptyOrWhitespaceOnly(passwd)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}
		if (StringUtils.isEmptyOrWhitespaceOnly(nickname)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}

		Calendar c = Calendar.getInstance();

		Connection conn = null;
		try {
			/*conn = new JNDIBBSConection().get();
			PreparedStatement stmt = null;*/
			// 检查用户名是否重复
			Configuration configuration = new Configuration().configure();
			SessionFactory factory = configuration.buildSessionFactory();
			Session session = factory.openSession();
			String hql = "select 1 from User where username =:username";
			// session.createQuery(hql).setParameter("username", username);
			List<Object> userList=session.createQuery(hql).setParameter("username", username).list();
			boolean isUsernameExists = false;
			while (userList!=null) {
				isUsernameExists = true;
				break;
			}
			if (isUsernameExists==false) {
				response.sendRedirect("./error?error=" + ErrorCode.USER_REGISTE_DUPLICATE);
				return;
			}
			Transaction tx = session.beginTransaction();
			String salt = Hashs.createSalt();
			long now = (int) (c.getTimeInMillis() / 1000);
			User user =new User();
			user.setUsername(username);
			user.setPasswd(DigestUtils.sha1Hex((salt + passwd).getBytes()));
			user.setNickname(nickname);
			user.setSalt(salt);
			user.setEmail(email);
			user.setGmtCreate(now);
			user.setIpReg(request.getRemoteAddr());
			user.setStatus(0);
			session.merge(user);
			tx.commit();
			// hql="insert into User
			// (username,passwd,salt,nickname,email,gmtCreate,ipReg,status)
			// values (?, ?, ?, ?, ?, ?, ?, 0)";
			/*stmt = conn.prepareStatement("insert into `stu_bbs`.`user` "
					+ "(`username`, `passwd`, `salt`, `nickname`, `email`, `gmt_create`, `ip_reg`, `status`) "
					+ "values (?, ?, ?, ?, ?, ?, ?, 0)");

			stmt.setString(1, username);
			stmt.setString(2, DigestUtils.sha1Hex((salt + passwd).getBytes()));
			stmt.setString(3, salt); // 散列值，64 位

			stmt.setString(4, nickname);
			stmt.setString(5, email);
			stmt.setLong(6, now);
			stmt.setString(7, request.getRemoteAddr());

			stmt.execute();
			stmt.close();*/
		}catch(Exception e){
			
		}
		response.sendRedirect("./login");
	}
}
